//
//  CustomCollection.m
//  The car
//
//  Created by 赵洋 on 14/11/18.
//  Copyright (c) 2014年 赵洋. All rights reserved.
//

#import "CustomCollection.h"
#import "CustomTableViewCell.h"
#import "Connection.h"
#import "RecommendModel.h"
@implementation CustomCollection
- (void)dealloc
{
    [_url release];
    [_array release];
    [_recommendtableview release];
    [super dealloc];
}

- (instancetype)initWithFrame:(CGRect)frame
{
    if (self = [super initWithFrame:frame]) {
        self.array = [NSMutableArray array];
        [self addObserver:self forKeyPath:@"url" options:NSKeyValueObservingOptionNew context:nil];
        self.recommendtableview = [[UITableView alloc] initWithFrame:CGRectMake(0, 0, self.contentView.frame.size.width, self.contentView.frame.size.height) style:UITableViewStylePlain];
        [_recommendtableview setRowHeight:100];
        [_recommendtableview registerClass:[CustomTableViewCell class] forCellReuseIdentifier:@"table"];
        _recommendtableview.delegate = self;
        _recommendtableview.dataSource = self;
        
        [self.contentView addSubview:_recommendtableview];

        
    }
    return self;
}

- (void)getconnection
{
    [Connection GetConnectWithUrl:self.url value:nil block:^(NSData *data) {
        NSMutableDictionary *dic = [NSJSONSerialization JSONObjectWithData:data options:NSJSONReadingMutableContainers error:nil];
        NSMutableDictionary *dic2 = [dic objectForKey:@"result"];
        NSMutableArray *arr = [dic2 objectForKey:@"newslist"];
        for (NSMutableDictionary *dic1 in arr) {
            RecommModel *model = [[RecommModel alloc] init];
            [model setValuesForKeysWithDictionary:dic1];
            [self.array addObject:model];
            [model release];
        }
        [_recommendtableview reloadData];
    }];
}

- (void)observeValueForKeyPath:(NSString *)keyPath ofObject:(id)object change:(NSDictionary *)change context:(void *)context
{
    if ([keyPath isEqualToString:@"url"]) {
        [self.array removeAllObjects];
        [self getconnection];
    }
}
- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section
{
    return [_array count];
}

- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath
{
    CustomTableViewCell *cell = [tableView dequeueReusableCellWithIdentifier:@"table" forIndexPath:indexPath];
    RecommModel *model = [_array objectAtIndex:indexPath.row];
    cell.model = model;
    return cell;
}


@end
